﻿using Microsoft.AspNetCore.SignalR;

namespace ChatBackend.Hubs
{
    /// <summary>
    /// 聊天器hub
    /// </summary>
    public class ChatHub : Hub
    {
        private static List<ClientUserDto> _clientUserl = new();

        private readonly ILogger<ChatHub> _logger;

        public ChatHub(ILogger<ChatHub> _logger)
        {
            this._logger = _logger;
        }

        /// <summary>
        /// 连接建立时
        /// </summary>
        /// <returns></returns>
        public override Task OnConnectedAsync()
        {
            //判断用户是否存在，否则添加集合
            if (!_clientUserl.Any(x => x.ConnectionId == Context.ConnectionId))
            {
                ClientUserDto obj = new ClientUserDto(Context.ConnectionId);
                _clientUserl.Add(obj);
            }

            //给所有人发送当前在线用户
            Clients.All.SendAsync("OnlineUserList", _clientUserl);
            return base.OnConnectedAsync();
        }

        /// <summary>
        /// 连接断开时
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override Task OnDisconnectedAsync(Exception? exception)
        {
            if (_clientUserl.Any(x => x.ConnectionId == Context.ConnectionId))
            {
                _clientUserl.Remove(_clientUserl.FirstOrDefault(x => x.ConnectionId == Context.ConnectionId));
            }

            //给所有人发送当前在线用户
            Clients.All.SendAsync("msg", _clientUserl);

            return base.OnDisconnectedAsync(exception);
        }
    }
}